// i.d(t, { g: () => RoomMesh })

import * as THREE from "three"
import RenderLayers from "../utils/RenderLayers"
import r from "../math/74384"
import ModelColliderTarget from "./ModelColliderTarget"
import configConst from "../constant/config.const"
import renderOrderEnum from "../enum/renderOrder.enum"

export default class RoomMesh extends ModelColliderTarget {
  _opacity: number
  _chunks: any[]
  size: THREE.Vector3
  center: THREE.Vector3
  built: boolean
  meshGroup: any
  meshSubgroup: any
  roomId: string
  constructor(e, t, i = RenderLayers.ALL) {
    super()
    this._opacity = 1
    this._chunks = []
    this.size = new THREE.Vector3()
    this.center = new THREE.Vector3()
    this.built = !1
    this.layers.mask = i.mask
    this.name = `RoomMesh:${e}-${t}`
    this.meshGroup = e
    this.meshSubgroup = t
    this.floorId = String(e)
    this.roomId = String(t)
    this.renderOrder = renderOrderEnum.default
  }
  dispose() {
    this.reset()
  }
  reset() {
    ;(this._chunks.length = 0), this.geometry.dispose(), (this.built = !1)
  }
  addChunk(e) {
    ;-1 === this._chunks.indexOf(e) && this._chunks.push(e)
  }
  getChunk(e) {
    return this._chunks[e]
  }
  build() {
    if (this.built) throw new Error("build() should only be called once")
    if (!this._chunks.length) return
    const e = r.qf(this._chunks.map(e => e.geometry))
    e.clearGroups()
    let t = 0
    this.material = []
    this._chunks.forEach((i, n) => {
      i.geometry &&
        i.geometry.index &&
        (e.addGroup(t, i.geometry.index.count, n),
        (t += i.geometry.index.count),
        i.geometry.dispose(),
        (i.geometry = e),
        i.notifyOnMaterialUpdated(e => {
          Array.isArray(this.material) && (this.material[n] = e)
        }),
        (i.onOpacityUpdate = e => {
          this.opacity = e
        }))
    })
    this.geometry = e
    this.geometry.computeBoundingBox()
    this.geometry.computeBoundingSphere()
    this.material = this._chunks.map(e => e.material)
    this.size = this.boundingBox.getSize(this.size)
    this.center = this.boundingBox.getCenter(this.center)
    this.built = !0
  }
  buildWithTileChunk(e) {
    if (!this.built) {
      this._chunks.push(e)
      e.notifyOnMaterialUpdated(e => {
        this.material = e
      })
      e.onOpacityUpdate = e => {
        this.opacity = e
      }
      this.size = this.boundingBox.getSize(this.size)
      this.center = this.boundingBox.getCenter(this.center)
      this.built = !0
    }
  }
  get boundingBox() {
    return r.A5(this.geometry)
  }
  set opacity(e) {
    e !== this.opacity &&
      ((this._opacity = e),
      (this.raycastEnabled = e > configConst.fadeConfig.FADE_CLICKABLE_THRESHOLD),
      (this.renderOrder = e < configConst.fadeConfig.FADE_OPAQUE ? renderOrderEnum.ghostFloor : renderOrderEnum.default))
  }
  get opacity() {
    return this._opacity
  }
  get chunks() {
    return this._chunks
  }
}
